# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: yuxuan, leon

from coin.strategy.mm.subscription import SubscriptionRequest
from coin.database.builder.archive_feed_cache_builder import ArchiveFeedCacheBuilder


class OkexV3ArchiveFeedCacheBuilderBase(ArchiveFeedCacheBuilder):
  _sub_request = None

  def __init__(self, products, columns, interval_ends):
    ArchiveFeedCacheBuilder.__init__(self, products, columns, interval_ends)

  @property
  def exchange(self):
    return 'Okex'

  def on_book_reset(self, book_builder_name, book_builder):
    if book_builder_name == self._sub_request:
      for product in self._products:
        book_builder.subscribe_instrument(product, self.on_feed)

  def _get_value(self, data, column):
    if column == 'open_interest':
      if data.open_interest is not None:
        return data.open_interest
      else:
        return None
    else:
      raise ValueError('Unknown field for Okex instrument %s' % column)

  def on_feed(self, instrument):
    map_data = {}
    for column in self._columns:
      value = self._get_value(instrument, column)
      if value is None:
        return
      map_data[column] = value
    self.on_feed_impl(instrument.timestamp, instrument.product, map_data)


class OkexV3FuturesArchiveFeedCacheBuilder(OkexV3ArchiveFeedCacheBuilderBase):
  _sub_request = SubscriptionRequest('Futures', 'Okex', 'v3')


class OkexV3SwapArchiveFeedCacheBuilder(OkexV3ArchiveFeedCacheBuilderBase):
  _sub_request = SubscriptionRequest('Futures', 'Okex', 'v3_swap')
